import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:go_router/go_router.dart';
import 'package:http/http.dart' as http;
import 'package:my_ebook_app/models/catalogue.dart';
import 'package:my_ebook_app/pages/theme_notifier.dart';
import 'package:provider/provider.dart';
import 'package:my_ebook_app/models/book.dart';
import 'package:my_ebook_app/common/epub_parser.dart';

class ReadingPage extends StatefulWidget {
  final ReadingBook book;

  final Catalogue bookCatalogue;

  const ReadingPage({Key? key, required this.book, required this.bookCatalogue}) : super(key: key);

  @override
  _ReadingPageState createState() => _ReadingPageState();
}

class _ReadingPageState extends State<ReadingPage> {
  List<String> _paragraphs = [];
  bool _isLoading = true;
  String? _errorMessage;

  double _fontSize = 16.0;
  double _lineHeight = 1.5;
  bool _showSettingsSheet = false;
  bool _showContentsSheet = false;
  late ScrollController _scrollController;
  double _progress = 0.0;
  double _currentCharOffsets = 0.0;
  int _currentChapterIndex = 0;
  List<double> _chapterOffsets = [];

  final Map<int, GlobalKey> _chapterKeys = {};

  double _totalScrollExtent = 0.0;

  Future<void> _updateBookProgress() async {
    try {
      double newProgress = _progress * 100;
      final response = await http.put(
        Uri.parse(
          'http://10.0.2.2:8080/bookDetail/setBookProgress?'
              'bookName=${widget.book.title}&progress=$newProgress',
        ),
      );
      if (response.statusCode == 200) {
        print('进度更新成功');
      } else {
        print('进度更新失败: ${response.statusCode}');
      }
    } catch (e) {
      print('错误: $e');
    }
  }

  @override
  void initState() {
    _scrollController = ScrollController();
    _scrollController.addListener(_updateProgress);
    super.initState();
    _loadEpubContent();
    _totalScrollExtent = widget.book.totalChar;
    _chapterOffsets = widget.bookCatalogue.bookCatalogues.values.toList();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _updateBookProgress();
    super.dispose();
  }

  void _updateProgress() {
    if (_scrollController.position.maxScrollExtent <= 0 || _isLoading) return;
    // 获取当前滚动位置
    final double scrollPosition = _scrollController.offset;
    // 计算当前进度 (0.0 - 1.0)
    double newProgress = double.parse(
        (scrollPosition / _totalScrollExtent)
            .clamp(0.0, 1.0)
            .toStringAsFixed(8)
    );
    setState(() {
      _progress = newProgress;
      _currentCharOffsets = scrollPosition;
    });
  }

  void _jumpToChapter(int chapterIndex) {
    if (chapterIndex < 0 || chapterIndex >= _paragraphs.length) return;
    _closeContentsSheet();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!_scrollController.hasClients) return;
      final context = _chapterKeys[chapterIndex]?.currentContext;
      if (context == null) {
        _scrollController.jumpTo( _chapterOffsets[chapterIndex]);
        return;
      }
      final renderObject = context.findRenderObject() as RenderBox?;
      if (renderObject == null) return;

      final viewport = RenderAbstractViewport.of(renderObject);
      final scrollPosition = viewport.getOffsetToReveal(renderObject, 0.0).offset;

      _scrollController.animateTo(
        scrollPosition,
        duration: Duration(milliseconds: 500),
        curve: Curves.easeInOut,
      );

      setState(() {
        _currentChapterIndex= chapterIndex;
      });
    });
    _updateProgress();
  }

  Future<void> _setLocalBookPath(String localPath) async {
    try {
      final response = await http.put(Uri.parse('http://10.0.2.2:8080/home/updateLocalBookAddress?bookName=${widget.book.title}&localBookAddress=$localPath'));
      if (response.statusCode == 200) {
        print('本地路径更新成功');
      } else {
        print('本地路径更新失败: ${response.statusCode}');
      }
    } catch (e) {
      print('错误: $e');
    }
  }

  Future<void> _loadEpubContent() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });
    try {String localPath;
      if (widget.book.localPath != null && await File(widget.book.localPath!).exists()) {
        localPath = widget.book.localPath!;
        print('使用现有EPUB文件: $localPath');
      } else {
        localPath = await EpubParser.downloadAndSaveEpub(widget.book);
        await _setLocalBookPath(localPath);
      }
      final chapters = await EpubParser.parseEpub(
          widget.book.title,localPath);

      setState(() {
        _paragraphs = chapters;
        _isLoading = false;
      });
      // 延迟一帧确保布局完成
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (_scrollController.hasClients) {
           double startPosition = widget.book.progress / 100 * _totalScrollExtent;
          _scrollController.jumpTo(startPosition);
          // 更新进度
          _updateProgress();
        }
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = '加载内容失败: ${e.toString()}';
      });
    }
  }

  void _toggleSettingsSheet() {
    setState(() {
      _showSettingsSheet = !_showSettingsSheet;
      if (_showSettingsSheet) _showContentsSheet = false;
    });
  }

  void _closeSettingsSheet() {
    if (_showSettingsSheet) {
      setState(() {
        _showSettingsSheet = false;
      });
    }
  }

  void _toggleContentsSheet() {
    setState(() {
      _showContentsSheet = !_showContentsSheet;
      if (_showContentsSheet) _showSettingsSheet = false;
    });
  }

  void _closeContentsSheet() {
    if (_showContentsSheet) {
      setState(() {
        _showContentsSheet = false;
      });
    }
  }

  void _increaseFontSize() {
    setState(() {
      _fontSize += 1.0;
    });
  }
  void _decreaseFontSize() {
    if (_fontSize > 12.0) {
      setState(() {
        _fontSize -= 1.0;
      });
    }
  }

  void _increaseLineHeight() {
    setState(() {
      _lineHeight = double.parse((_lineHeight + 0.1).toStringAsFixed(1));
    });
  }

  void _decreaseLineHeight() {
    if (_lineHeight > 1.0) {
      setState(() {
        _lineHeight = double.parse((_lineHeight - 0.1).toStringAsFixed(1));
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final isDarkMode = Theme.of(context).brightness == Brightness.dark;
    return Scaffold(
      body: Stack(
        children: [
          Column(
            children: [
              _buildAppBar(context,isDarkMode),
              Expanded(
                child: ListView(
                  controller: _scrollController,
                  padding: EdgeInsets.only(top: 5),
                  children: [
                    ..._buildTextParagraphs(isDarkMode),
                  ],
                ),
              ),
              _buildProgressSection(isDarkMode),
            ],
          ),

          // 设置弹窗遮罩
          if (_showSettingsSheet || _showContentsSheet)
            GestureDetector(
              onTap: _showSettingsSheet ? _closeSettingsSheet : _closeContentsSheet,
              child: Container(
                color: Colors.black54,
              ),
            ),

          // 设置弹窗（从底部滑出）
          AnimatedPositioned(
            duration: Duration(milliseconds: 300),
            curve: Curves.easeOut,
            bottom: _showSettingsSheet ? 0 : -300,
            left: 0,
            right: 0,
            child: _buildSettingsSheet(isDarkMode),
          ),

          // 目录弹窗（从底部滑出）
          AnimatedPositioned(
            duration: Duration(milliseconds: 300),
            curve: Curves.easeOut,
            bottom: _showContentsSheet ? 0 : -500,
            left: 0,
            right: 0,
            child: _buildContentsSheet(isDarkMode),
          ),
        ],
      ),
    );
  }

  PreferredSizeWidget _buildAppBar(BuildContext context,bool isDarkMode) {
    return AppBar(elevation: 1, toolbarHeight: 47,
      title: Center(child:  Text(widget.book.title,
          style: TextStyle(color: isDarkMode?Colors.grey[500] : Colors.black,
              fontSize: 20.0, fontWeight: FontWeight.bold),
        ),
      ),
      leading: IconButton(icon: Icon(Icons.arrow_back,
            color: isDarkMode?Colors.grey[500] : Colors.black,
          ),
          onPressed: () async {await _updateBookProgress();context.pop('progress_updated');
          }
      ),
      actions: [IconButton(icon: Icon(Icons.more_vert,
            color: isDarkMode?Colors.grey[500] : Colors.black,
          ),
          onPressed: _toggleSettingsSheet,
        ),
      ],
    );
  }

  List<Widget> _buildTextParagraphs(bool isDarkMode) {
    if (_isLoading) {
      return [
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 20),
          child: Center(child: CircularProgressIndicator()),
        )
      ];
    }

    if (_errorMessage != null) {
      return [
        Padding(
            padding: const EdgeInsets.all(20.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.error_outline, size: 50, color: Colors.red),
                SizedBox(height: 20),
                Text(_errorMessage!,
                  style: TextStyle(fontSize: 18, color: Colors.red),
                  textAlign: TextAlign.center,
                ),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: _loadEpubContent,
                  child: Text('重试'),
                )
              ],
            )
        )
      ];
    }

    if (_paragraphs.isEmpty) {
      return [
        Padding(
            padding: const EdgeInsets.all(20),
            child: Center(child: Text('暂无内容',
              style: TextStyle(fontSize: 18),
            ),
            )
        )
      ];
    }

    return List.generate(_paragraphs.length, (index) {
      _chapterKeys[index] = GlobalKey();
      final chapter = _paragraphs[index];
      final paragraphs = chapter.split(' ');

      return Column(
        key: _chapterKeys[index],
        children: paragraphs.map((para) {
          if (para.trim().isEmpty) return SizedBox(height: 10);

          bool isFirstPartOrChapter = RegExp(r'^\s*第\d+[部章]').hasMatch(para) ||
              RegExp(r'^\s*第([一二三四五六七八九十]+)[部章]').hasMatch(para);

          return Container(
            width: double.infinity,
            child:  Column(
              crossAxisAlignment: isFirstPartOrChapter ? CrossAxisAlignment.center : CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: EdgeInsets.only(left: isFirstPartOrChapter ? 0 : 15, right: isFirstPartOrChapter ? 35 : 10),
                  child: RichText(
                    textAlign: TextAlign.start,
                    text: TextSpan(
                      style: TextStyle(
                        fontSize: isFirstPartOrChapter ? _fontSize + 4 : _fontSize,
                        color: isDarkMode ? Colors.grey[300] : Colors.black87,
                        height: _lineHeight,
                      ),
                      children: [
                        const TextSpan(text: '　　'),
                        TextSpan(text: para),
                      ],
                    ),
                  ),
                ),
                SizedBox(height: _lineHeight * 4),
              ],
            ),
          );
        }).toList(),
      );
    });
  }

  Widget _buildProgressSection(bool isDarkMode) {
    // 计算百分比和章节位置
    final double percentage = _progress * 100;
    // 找到当前阅读的章节
    for (int i = 0; i < _chapterOffsets.length; i++) {
      if (_currentCharOffsets >= _chapterOffsets[i]) {
        _currentChapterIndex = i;
      } else {
        break;
      }
    }
    final int totalChapters = _paragraphs.length;
    final int currentChapter = _currentChapterIndex + 1;

    return Container(height: 58, width: double.infinity,
      color: isDarkMode ? Color(0xFF32333E) : Color(0xFFF6EEFA),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Text('${percentage.toStringAsFixed(1)}%', // 显示百分比
              style: TextStyle(fontSize: 14.0,
                color: isDarkMode ? Colors.grey[500] : Colors.black,),
            ),
            SizedBox(width: 200, height: 6,
              child: ClipRRect(borderRadius: BorderRadius.circular(10),
                child: LinearProgressIndicator(value: _progress, // 使用实时进度值
                  backgroundColor: isDarkMode ? Colors.grey[500] : Colors.white,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),),
              ),
            ),
            Text('$currentChapter/$totalChapters', // 显示当前章/总章数
              style: TextStyle(fontSize: 14.0, color: isDarkMode ? Colors.grey[500] : Colors.black,),
            ),
          ]
      ),
    );
  }

  Widget _buildSettingsSheet(bool isDarkMode) {
    return Material(elevation: 10,
      borderRadius: BorderRadius.only(
        topLeft: Radius.circular(20),
        topRight: Radius.circular(20),
      ),
      child: Container(padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
        decoration: BoxDecoration(
          color: isDarkMode? Color(0xFF32383E) : Color(0xFFF6EEFA),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Center(
              child: Container(
                width: 40,
                height: 5,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(5),
                ),
              ),
            ),
            SizedBox(height: 15),
            // 目录按钮
            InkWell(
              onTap: () {
                _closeSettingsSheet();
                _toggleContentsSheet();
              },
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 8),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                        child: Row(
                          children: [
                            Icon(Icons.list, size: 26),
                            SizedBox(width: 8),
                            Text('目录', style: TextStyle(fontSize: 18)),
                          ],
                        )
                    ),
                    Icon(Icons.keyboard_arrow_right, size: 24)
                  ],
                ),
              ),
            ),
            Divider(),
            // 深色模式开关
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                    child: Row(
                      children: [
                        Icon(isDarkMode? Icons.dark_mode_outlined : Icons.light_mode_outlined,
                            size: 24
                        ),
                        SizedBox(width: 8),
                        Text('深色模式', style: TextStyle(fontSize: 18)),
                      ],
                    )
                ),
                Transform.scale(
                    scale: 0.9,
                    child: Consumer<ThemeNotifier>(
                      builder: (context, themeNotifier, child) {
                        return Transform.scale(
                          scale: 0.9,
                          child: Switch(
                            value: themeNotifier.themeMode == ThemeMode.dark,
                            onChanged: (value) {
                              themeNotifier.setThemeMode(
                                  value ? ThemeMode.dark : ThemeMode.light
                              );
                            },
                            activeColor: Colors.blue,
                          ),
                        );
                      },
                    )
                )
              ],
            ),
            Divider(),
            // 字体大小调整
            Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(child: Row(
                      children: [
                        Icon(Icons.font_download_outlined, size: 24),
                        SizedBox(width: 8),
                        Text('字体大小', style: TextStyle(fontSize: 18)),
                      ],
                    )
                ),
                Row(children: [
                    IconButton(
                      icon: Icon(Icons.remove_circle_outline, color: Colors.blue, size: 22,),
                      onPressed: _decreaseFontSize,
                    ),
                    Text('${_fontSize.toInt()}', style: TextStyle(fontSize: 18),
                    ),
                    IconButton(icon: Icon(Icons.add_circle_outline, color: Colors.blue, size: 24,),
                      onPressed: _increaseFontSize,
                    ),
                  ],
                ),
              ],
            ),
            Divider(),
            // 行间距调整
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                    child: Row(
                      children: [
                        Icon(Icons.format_line_spacing, size: 24),
                        SizedBox(width: 8),
                        Text('行间距', style: TextStyle(fontSize: 18)),
                      ],
                    )
                ),

                Row(
                  children: [
                    IconButton(
                      icon: Icon(Icons.remove_circle_outline,
                        color: Colors.blue,
                        size: 22,
                      ),
                      onPressed: _decreaseLineHeight,
                    ),
                    Text('${_lineHeight}',
                      style: TextStyle(fontSize: 18),
                    ),
                    IconButton(
                      icon: Icon(Icons.add_circle_outline,
                        color: Colors.blue,
                        size: 24,
                      ),
                      onPressed: _increaseLineHeight,
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildContentsSheet(bool isDarkMode) {
    final chapters = widget.bookCatalogue.bookCatalogues.keys.toList();
    return Material(elevation: 10,
      borderRadius: BorderRadius.only(
        topLeft: Radius.circular(20),
        topRight: Radius.circular(20),
      ),
      child: Container(height: 500,
        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
        decoration: BoxDecoration(
          color:isDarkMode? Color(0xFF32383E) : Color(0xFFF6EEFA),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Center(
              child: Container(width: 40, height: 5,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(5),
                ),
              ),
            ),
            SizedBox(height: 20),
            Text('目录',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 10),
            Expanded(
              child: ListView.builder(itemCount: chapters.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(chapters[index]),
                    onTap: () => _jumpToChapter(index),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
